<template>
  <el-dialog v-model="model" title="添加新地址" width="40%">
    <el-form :model="addressForm" ref="addressFormRef" label-width="80px">
      <el-form-item label="收货人" prop="consignee">
        <el-input v-model="addressForm.consignee" placeholder="请输入收货人"></el-input>
      </el-form-item>
      <!-- 省份 -->
      <el-form-item label="省份" prop="province">
        <el-select v-model="addressForm.province" placeholder="请选择省份" @change="onProvinceChange" style="width: 100%">
          <el-option v-for="item in provinces" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 城市 -->
      <el-form-item label="城市" prop="city">
        <el-select v-model="addressForm.city" placeholder="请选择城市" @change="onCityChange" style="width: 100%">
          <el-option v-for="item in cities" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 区县 -->
      <el-form-item label="区县" prop="district">
        <el-select v-model="addressForm.district" placeholder="请选择区县" style="width: 100%">
          <el-option v-for="item in districts" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="detail">
        <el-input v-model="addressForm.detail" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="model = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import regions from '@/assets/data/pca.json';
// import { useUserStore } from '@/stores/user';
// const userStore = useUserStore();
axios.defaults.baseURL = "http://localhost:8080";

const model = defineModel();

const addressForm = ref({
  consignee: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  phone: ''
});

const addressFormRef = ref(null);
const emit = defineEmits(['confirm']);

// 省市区数据
const provinces = ref([]);
const cities = ref([]);
const districts = ref([]);

// 初始化省份列表
onMounted(() => {
  for (const key in regions) {
    if (regions.hasOwnProperty(key)) {
      provinces.value.push({ label: key, value: key });
    }
  }
});

const onProvinceChange = (selectedProvince) => {
  const selectedProvinceData = regions[selectedProvince];
  if (selectedProvinceData) {
    cities.value = Object.keys(selectedProvinceData).map(cityKey => ({
      label: cityKey,
      value: cityKey
    }));
    addressForm.value.city = '';
    addressForm.value.district = '';
  } else {
    cities.value = [];
    districts.value = [];
  }
};

const onCityChange = (selectedCity) => {
  const selectedCityData = regions[addressForm.value.province]?.[selectedCity];
  if (selectedCityData) {
    districts.value = selectedCityData.map(district => ({
      label: district,
      value: district
    }));
    addressForm.value.district = '';
  } else {
    districts.value = [];
  }
};

// 对话框关闭时清空表单
watch(model, (val) => {
  if (!val) {
    addressForm.value = {
      consignee: '',
      province: '',
      city: '',
      district: '',
      detail: '',
      phone: ''
    };
    cities.value = [];
    districts.value = [];
  }
});

const handleConfirm = async () => {
  const form = addressForm.value;

  if (!form.consignee) return ElMessage.error('请输入收货人姓名');
  if (!form.province) return ElMessage.error('请选择省份');
  if (!form.city) return ElMessage.error('请选择城市');
  if (!form.district) return ElMessage.error('请选择地区/行政区');
  if (!form.detail) return ElMessage.error('请输入详细地址');
  if (!form.phone) return ElMessage.error('请输入手机号码');

  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(form.phone)) return ElMessage.error('请输入正确的手机号码');

  const token = sessionStorage.getItem('token');
  axios.post('/address/add', form, {
    headers: {
      Authorization: `${token}`
    }
  }).then(response => {
    if (response.data.code === 0) {
      ElMessage.success('地址添加成功');
      // 更新用户地址列表
      // userStore.fetchUserAddress();
      emit('confirm', addressForm.value);
      model.value = false;
    } else {
      ElMessage.error(response.data.message);
    }
  }).catch(error => {
    console.error('添加地址失败:', error);
    ElMessage.error('添加地址失败');
  });


};
</script>